package wedaex.controller;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringEscapeUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.Controller;
import org.springframework.web.servlet.view.RedirectView;

import wedaex.content.Page;
import wedaex.content.SimpleGetContentSource;
import wedaex.remote.handler.RegExpExtractHandler;

/**
 * @deprecated not used any more, moved to {@link RegExpExtractHandler}
 */
public class ExtractController implements Controller {

	public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception {
		String url = request.getParameter("url");
		String re = StringEscapeUtils.unescapeHtml(request.getParameter("regularExpression"));
		if(StringUtils.isBlank(url) || StringUtils.isBlank(re))
			return new ModelAndView(new RedirectView("index.wdx"));
		
		SimpleGetContentSource source = SimpleGetContentSource.create(url);
		Page page = source.retrieveContent();
		
		Pattern p = Pattern.compile(re, Pattern.CASE_INSENSITIVE|Pattern.DOTALL);
		Matcher m = p.matcher(page.getContent());
		
		String result = "not found";
		if(m.find()) {
			result = m.group(1);
		}
		ModelAndView mv = new ModelAndView("extract");
		mv.addObject("url", StringEscapeUtils.escapeHtml(url));
		mv.addObject("result", StringEscapeUtils.escapeHtml(result));
		return mv;
	}

}
